<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/10/6
 * Time: 12:59
 */

namespace Admin\Controller;


use Common\Common\FileSystem;
use Common\Common\ResponseResult;
use Common\Common\Validator;
use Common\Model\Auth;

class AdminIndexController extends Controller
{
    /**
     * 首页
     */
    public function index()
    {
        $this->checkPermission('admin');
        $this->display('admin/index');
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        if (IS_POST && Auth::logout()) {
            ResponseResult::success('Logout Is Successfully');
        }
        ResponseResult::error(1000, 'Logout Is Failed');
    }

    public function userProfile()
    {
        $this->assign('user', Auth::user());
        $this->display('admin/profile');
    }

    public function updateProfile()
    {
        if (IS_POST) {
            $validator = Validator::make($_POST, [
                'username' => ['required', 'max:32', 'min:4', 'unique:users,username,' . $_POST['id']],
                'email' => ['required', 'email', 'unique:users,email,' . $_POST['id']],
                'password' => ['max:32', 'min:8'],
                'avatar' => ['file:image'],
                'age' => ['integer', 'between:1,200'],
                'sex' => ['integer', 'between:0,1']
            ]);
            if ($validator->filed()) {
                $this->error('参数错误', '/admin/user/list');
            }
            $data = array_only($_POST, ['username', 'password', 'age', 'sex', 'email']);
            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $data['avatar'] = FileSystem::uploadFile('avatar');
            }
            $user = Auth::user();
            if (in_array('password', array_keys($data))) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            if ($user->update($data)) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        } else {
            $this->error('请求错误');
        }
    }
}